package com.leetcode.dfs;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class SubsetsWithDup {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        Arrays.sort(nums);
        dfs(nums, 0, new boolean[nums.length]);
        return resList;
    }

    List<List<Integer>> resList = new ArrayList<>();
    List<Integer> subList = new ArrayList<>();

    private void dfs(int[] nums, int ind, boolean[] used) {
        resList.add(new ArrayList<>(subList));
        if (ind >= nums.length) {
            return;
        }
        for (int i = ind; i < nums.length; i++) {
            if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) {
                continue;
            }
            subList.add(nums[i]);
            used[i] = true;
            dfs(nums, i + 1, used);
            subList.remove(subList.size() - 1);
            used[i] = false;
        }
    }
}
